package com.netease.mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * Tomcat启动类：
 * <p>
 * Tomcat的处理流程：把URL对应处理的Servlet关系形成，解析HTTP协议，封装请求/响应对象，
 * 利用反射实例化具体的Servlet进行处理即可。
 */
public class MyTomcat {
    private Integer port = 8080;

    private Map<String, String> urlServeltMapping = new HashMap<>();

    public MyTomcat(Integer port) {
        this.port = port;
    }

    public void start() {
        initServeltMapping();

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("MyTomcat is Starting...");
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();

                MyRequest myRequest = new MyRequest(inputStream);
                MyResponse myResponse = new MyResponse(outputStream);

                //请求分发
                dispatch(myRequest, myResponse);
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void initServeltMapping() {
        for (ServeletMapping serveletMapping : ServletMappingConfig.serveletMappingList) {
            urlServeltMapping.put(serveletMapping.getUrl(), serveletMapping.getClazz());
        }
    }

    public void dispatch(MyRequest myRequest, MyResponse myResponse) {
        String clazz = urlServeltMapping.get(myRequest.getUrl());

        // 反射
        try {
            Class<MyServelet> myServeltClass = (Class<MyServelet>) Class.forName(clazz);
            MyServelet myServelet = myServeltClass.newInstance();
            myServelet.service(myRequest, myResponse);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyTomcat myTomcat = new MyTomcat(8080);
        myTomcat.start();
    }

    /**
     * MyTomcat is Starting...
     * MyRequest{url='/girl', method='GET'}
     * MyRequest{url='/world', method='GET'}
     */
}
